import { PokerCard, PokerCardOpt } from "../Poker/PokerCard.js";
import { PokerServer } from "../Poker/PokerServer.js";
import { MsgData, getPokerCardsType } from "../Poker/Rule.js";

/** 用户信息 */
export interface PlayerInfo {
  /** 用户名称 */
  userName: string;
}

export interface ClientPlayerOpt {
  /** 页面容器dom的id */
  domId: string;
  /** 上家的用户信息 */
  RHO: PlayerInfo;
  /** 下家的用户信息 */
  LHO: PlayerInfo;
  /** 扑克服务 */
  server: PokerServer;
}
export class ClientPlayer {
  private server: PokerServer;
  /** 需要绘制的div */
  public domId = "";
  /** 上家的用户信息 */
  public RHO: PlayerInfo;
  /** 下家的用户信息 */
  public LHO: PlayerInfo;
  /** 用户手里的牌集合 */
  public cards: PokerCard[] = [];
  /** 被选中的牌 */
  public currCards: PokerCard[] = [];
  constructor({ domId, RHO, LHO, server }: ClientPlayerOpt) {
    this.domId = domId;
    this.RHO = RHO;
    this.LHO = LHO;
    this.server = server;
    this.renderLayout();

    this.server.onMsg((msg: string) => {
      this.onMsgData(msg);
    });

    this.server.receive(JSON.stringify({ type: "start", data: {} }));
  }

  public receive(cards: PokerCard[]) {
    this.cards = cards;
  }

  private setCards(cards: PokerCard[]) {
    this.cards = cards;
    this.renderCards();
  }

  /** 绘制布局 */
  private renderLayout() {
    const dom = document.querySelector("#" + this.domId);
    if (dom) {
      dom.innerHTML = `<div>
        <div class="poker-player-b">
          <div class="">${this.RHO.userName}</div>
        </div>
        <div class="poker-player-a">
          <div class="">${this.LHO.userName}</div>
        </div>
        <div class="poker-player-self">
          <div class="">
            <div class="poker-btns">
              <div class="J_run">出牌</div>
            </div>
            <div class="poker-card-list J_poker-card-list"></div>
          </div>
        </div>
      </div>`;

      const domRun = dom.querySelector(".J_run") as HTMLElement;
      if (domRun) {
        domRun.onclick = () => this.run();
      }
    }
  }

  /** 绘制手牌 */
  private renderCards() {
    const dom = document.querySelector(".J_poker-card-list");
    if (dom) {
      dom.innerHTML = this.cards
        .map(
          (v, i) =>
            `<div class="poker-card-my" data-index="${i}">${
              ["小丑", "黑桃", "红桃", "梅花", "方块"][v.type]
            } ${v.label}</div>`
        )
        .join("");

      dom.querySelectorAll<HTMLElement>(".poker-card-my").forEach((el, index) => {
        el.onclick = () => {
          el.classList.toggle("active");
        };
      });
    }
  }

  /** 监听服务端的信息 */
  public onMsgData(msg: string) {
    let data: MsgData = {} as MsgData;
    try {
      data = JSON.parse(msg) || {};
    } catch (err) {
      console.warn(err);
    }

    // 上家出牌信息
    if (data?.type === "RHO") {
    }
    // 下家出牌信息
    if (data?.type === "LHO") {
    }
    // 自己的出牌信息
    if (data?.type === "player") {
    }
    // 收到自己的牌
    if (data?.type === "deal") {
      console.log("deal", data.data);
      console.log(this);
      this.setCards(
        (data.data as PokerCardOpt[]).map((v) => new PokerCard(v)).sort((a, b) => b.value - a.value)
      );
    }
  }

  /** 运行(点击出牌) */
  private async run() {
    const cards: PokerCard[] = [];
    document.querySelectorAll<HTMLElement>(".poker-card-my.active").forEach((el) => {
      cards.push(this.cards[Number(el.dataset.index)]);
    });
    const type = await getPokerCardsType(cards);
    console.log("type", type, type.__proto__.constructor.name);
    if (type.__proto__.constructor.name !== "ErrorPokerHand") {
      this.server.receive(
        JSON.stringify({
          type: "player",
          data: {
            type: type.__proto__.constructor.name,
            cards: cards.map((v) => ({
              type: v.type,
              val: v.value,
            })),
          },
        })
      );
    }
  }
}
